from conn import *
from protocol.IPacket import *
import time

ignoreCmd = (0x2022, 0x202e)

class packetVec():

	def __init__(self, ip, port):
		self.conn = Conn()
		self.conn.connect(ip, port)
		self.header = ""
		self.packets = []

	def D_printPacketsList(self):
		print "=begin==",
		for p in self.packets:
			print "%x, " % p.getPacketCmd(),
		print "===end"

	def checkPacket(self):
		allLen = 0
		try:
			buffer = self.conn.recv()
			if buffer :
				buffer = self.header + buffer
			while(1):
				if len(buffer) < 8:
					self.D_printPacketsList()
					break			
				input = ESInputPacket(buffer)
				length = input.getPacketLength()
				cmd = input.getPacketCmd()
				buffer = buffer[length+8:]
				if cmd in ignoreCmd:
					continue
				print "### in cmd:%x" % cmd
				self.packets.append(input)
			self.header = buffer
		except:
			return None

	def __getFirst(self):
		self.checkPacket()
		if len(self.packets) <= 0:
			return None
		packet = self.packets[0]
		self.packets = self.packets[1:]
		return packet

	def getPacketNum(self):
		num = len(self.packets)
		return num

	def getPacket(self, cmds = []):
		if cmds :
			packet = self.__getFirst()
			if packet :
				cmd = packet.getPacketCmd()
				if cmd in cmds:
					self.D_printPacketsList()
					return packet
			return None
		else :
			self.D_printPacketsList()
			return self.__getFirst()

	def recv(self):
		self.__checkPacket()
		print len(self.packets)
		packet = self.getPacket()
		return packet

	def send(self, buffer):
		return self.conn.send(buffer)

	def recvAllPacket(self):
		pass
